import { ContextType, createParamDecorator, ExecutionContext } from '@nestjs/common';
import { TokenEntity } from 'src/api/auth/entities/token.entity';
import { UserEntity } from 'src/api/user/entities/user.entity';

export const CurUser = createParamDecorator(async (data, execution: ExecutionContext) => {
  // 请求类型
  // const type = execution.getType<ContextType>();
  // console.log('2022-10-08 11:23:40', type);
  const req = execution.switchToHttp().getRequest();
  const { token } = req.headers;
  const qb = await UserEntity.getRepository().createQueryBuilder('user');
  // const res = await qb
  //   .innerJoinAndSelect('user.userRoles', 'userRoles')
  //   .leftJoinAndSelect(TokenEntity, 'token')
  //   .where('token.token = :token')
  //   .setParameter('token', token)
  //   .getOne();
  const res = await qb
    .where((qb) => {
      const userId = qb
        .subQuery()
        .select('token.user_id')
        .from(TokenEntity, 'token')
        .where('token.token = :token')
        .getQuery();
      return 'user.id = ' + userId;
    })
    .innerJoinAndSelect('user.userRoles', 'userRoles')
    .setParameter('token', token)
    .getOne();
  return res;
});
